<template>
  <transition enter-active-class="slideInUp faster animated" leave-active-class="slideOutDown faster animated">
    <div class="tipModule" v-show="isShowAni">
      <div class="tipBox publicVCenter">
        <!-- 头部和关闭按钮 -->
        <img src="@/assets/image/popupArea/closeIcon.png" class="closeIcon" v-tap="{ methods: closePopupModule }" />
        <div class="tip-title-wrapper">
          打赏歌手
        </div>

        <!-- 歌手轮播区域 -->
        <div class="singer-carousel-container">
          <div class="arrow left-arrow" :class="{ 'is-disabled': singerList.length <= 1 }" v-tap="{ methods: navigate, direction: -1 }"></div>

          <div class="singer-carousel-wrapper">
            <div class="singer-carousel" ref="singerCarousel" @scroll.passive="handleScroll">
              <div
                class="singer-item"
                :class="{ selected: currentTipSingerId === singer.awardid }"
                v-for="(singer, index) in displaySingerList"
                :key="singer.awardid + '-' + index"
                v-tap="{ methods: handleSelectSinger, singerId: singer.awardid }"
              >
                <div class="singer-name-banner">{{ singer.name || '未知歌手' }}</div>
                <img :src="singer.avator" class="singer-image" />
                <img v-if="currentTipSingerId === singer.awardid" src="@/assets/image/popupArea/tickIcon.png" class="tick-icon" />
              </div>
            </div>
          </div>

          <div class="arrow right-arrow" :class="{ 'is-disabled': singerList.length <= 1 }" v-tap="{ methods: navigate, direction: 1 }"></div>
        </div>

        <!-- 返回按钮容器 -->

        <!-- 分页器 (小圆点) -->
        <div class="pagination-dots">
          <span
            v-for="(singer, index) in singerList"
            :key="singer.awardid"
            class="dot"
            :class="{ active: currentSingerIndex === index }"
          ></span>
        </div>
        <div class="return-button-container">
          <div class="return-button" v-tap="{ methods: closePopupModule }">
            <span class="return-text">返回</span>
            <img src="@/assets/image/hdBar/backicon.png" class="return-icon" />
          </div>
        </div>

        <!-- Tab 容器 -->
        <div class="tab-container publicVCenter">
          <div class="tab-item publicVCenter active">打赏</div>
        </div>

        <!-- 礼物选择区域 -->
        <div class="giftListWrap">
          <swipe class="gift-swipe" :auto="0">
            <swipe-item class="page" :key="index" v-for="(group, index) in tipGiftListFormat">
              <div
                v-for="gift in group"
                class="item publicHvCenter"
                :key="gift.giftId"
                v-tap="{ methods: chooseGiftType, giftId: gift.giftId }"
              >
                <img class="giftImg" :src="gift.giftImg" :class="{ active: gift.giftId === currentTipGiftType }" />
                <div class="name">{{ gift.name }}</div>
                <div class="price publicHvCenter" v-show="enterEffect !== gift.giftId">
                  <span class="rmb">¥</span>{{ gift.price }}
                </div>
                <div class="activeBox publicHvCenter" v-show="gift.giftId === currentTipGiftType"></div>
              </div>
            </swipe-item>
          </swipe>
        </div>

        <!-- 输入框区域 -->
        <div class="txtWrap publicHCenter">
          <textarea
            v-model="content"
            :maxlength="canCustomizeInput ? 20 : 0"
            ref="text"
            cols="30"
            rows="10"
            placeholder="请输入留言内容(20字以内)"
            v-on:blur="handleBlur"
          ></textarea>
          <div class="ylBtn publicHvCenter" v-tap="{ methods: ganerateRandomWish }">语录</div>
        </div>

        <!-- 底部按钮区域 -->
        <div class="btnWrap publicVCenter">
          <input
            type="text"
            class="selectDeskInput"
            placeholder="桌号"
            :value="tipDeskNum"
            @input="handleDeskInput"
          />
          <div class="sendBtn publicHvCenter" v-tap="{ methods: handleSend }">赠送</div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
import { Swipe, SwipeItem } from 'vue-swipe';
import { getSingerList } from '@/api/music/index';
import { QUICKWISH } from '@/assets/constant/index';
import { timeoutTask, generateRandom } from '../../utils';

const wx = require('weixin-js-sdk');

const quickWishLen = QUICKWISH.length;

export default {
  name: 'tipPopup',
  components: {
    Swipe,
    SwipeItem,
  },
  computed: {
    ...mapState({
      singerList: (state) => state.app.singerList,
      currentTipSingerId: (state) => state.app.currentTipSingerId,
      tipGiftList: (state) => state.app.tipGiftList,
      currentTipGiftType: (state) => state.app.currentTipGiftType,
      enterEffect: (state) => state.user.enterEffect,
      tipDeskNum: (state) => state.app.tipDeskNum,
      canCustomizeInput: (state) => state.app.canCustomizeInput,
    }),

    // NEW: This computed property will be used for rendering the carousel
    displaySingerList() {
      const list = this.singerList;
      if (list.length <= 1) {
        return list; // No need to loop if there's only one or zero items
      }
      // Clone the last item and put it at the start
      const first = list[0];
      // Clone the first item and put it at the end
      const last = list[list.length - 1];
      return [last, ...list, first];
    },
    selectedSingerName() {
      if (!this.currentTipSingerId) {
        return '';
      }
      const singer = this.singerList.find((s) => s.awardid === this.currentTipSingerId);
      return singer ? singer.name : '';
    },
    currentSingerIndex() {
      if (!this.currentTipSingerId || this.singerList.length === 0) return -1;
      return this.singerList.findIndex((s) => s.awardid === this.currentTipSingerId);
    },
    // 将 tipGiftList 格式化成二维数组（每页8个礼物）
    tipGiftListFormat() {
      if (!this.tipGiftList || this.tipGiftList.length === 0) {
        return [];
      }
      const result = [];
      let tempArr = [];
      for (let i = 0; i < this.tipGiftList.length; i += 1) {
        tempArr.push(this.tipGiftList[i]);
        if ((i !== 0 && (i + 1) % 8 === 0) || i === this.tipGiftList.length - 1) {
          result.push(tempArr);
          tempArr = [];
        }
      }
      return result;
    },
  },
  watch: {
    // 监听弹窗显示状态，每次打开时刷新数据
    isShowAni(newVal) {
      if (newVal) {
        this.fetchSingerList();
      }
    },
    // 监听可自定义输入权限变化
    canCustomizeInput(newVal) {
      if (!newVal) {
        this.content = '';
      }
    },
    // Modify the watcher to handle the initial scroll
    singerList(newList) {
      if (newList.length > 1) {
        // When the list is loaded, silently move to the first REAL item
        this.$nextTick(() => {
          this.scrollToSinger(0, 'auto'); // Scroll to the original first item's position
        });
      }
    },
    // 当 vuex 中的歌手 ID 变化时，执行滚动
    currentTipSingerId(newId) {
      const newIndex = this.singerList.findIndex((s) => s.awardid === newId);
      if (newIndex !== -1) {
        this.$nextTick(() => {
          // 调用我们保留的滚动方法
          this.scrollToSinger(newIndex, 'smooth'); // Smooth scroll to the target
        });
      }
    },
  },
  data() {
    return {
      isShowAni: false,
      content: '',
      scrollTimeout: null, // 用于判断滚动是否停止的计时器
    };
  },
  mounted() {
    // 执行弹出动画
    this.showAniStart();
  },
  methods: {
    ...mapMutations({
      togglePopup: 'app/togglePopup',
      setSingerList: 'app/setSingerList',
      setCurrentTipSingerId: 'app/setCurrentTipSingerId',
      setCurrentTipGiftType: 'app/setCurrentTipGiftType',
      setTipDeskNum: 'app/setTipDeskNum',
    }),
    showAniStart() {
      this.isShowAni = true;
    },
    hideAniStart() {
      this.isShowAni = false;
    },
    closePopupModule() {
      this.hideAniStart();
      timeoutTask(() => {
        this.togglePopup();
      }, 200);
    },
    // 获取歌手列表
    fetchSingerList() {
      getSingerList()
        .then((res) => {
          const singerList = res.singerList || res.list || [];
          this.setSingerList(singerList);
          // 如果没有选中歌手且有列表，默认选中第一个
          if (singerList.length > 0 && !this.currentTipSingerId) {
            this.setCurrentTipSingerId(singerList[0].awardid);
          }
        })
        .catch((err) => {
          console.error('获取歌手列表失败:', err);
        });
    },
    // UPDATE scrollToSinger to accept a behavior option
    scrollToSinger(originalIndex, behavior = 'smooth') {
      const carousel = this.$refs.singerCarousel;
      // We add 1 because of the cloned item at the beginning
      const displayIndex = originalIndex + 1;
      if (carousel && carousel.children[displayIndex]) {
        const item = carousel.children[displayIndex];
        const scrollLeft = item.offsetLeft - (carousel.offsetWidth / 2) + (item.offsetWidth / 2);
        carousel.scrollTo({ left: scrollLeft, behavior });
      }
    },
    // handleSelectSinger might need a small tweak to ensure correct scrolling
    handleSelectSinger(p) {
      const { singerId } = p;
      // No need to do anything if already selected
      if (this.currentTipSingerId === singerId) return;

      // This will trigger the watcher, which now handles scrolling correctly
      this.setCurrentTipSingerId(singerId);
    },
    // navigate method (全新版本)
    navigate(p) {
      const { direction } = p; // direction is -1 for left, 1 for right
      const carousel = this.$refs.singerCarousel;

      if (!carousel || !carousel.children || carousel.children.length < 2) {
        // Cannot calculate step if there are not enough items
        return;
      }

      // --- Start of new logic ---

      // We calculate the distance to scroll for one full "step".
      // This is the width of one singer item plus its margin.
      // We use the second and third items (display index 1 and 2) because they are guaranteed to be real items.
      const itemWidth = carousel.children[1].offsetWidth;
      const itemMargin = carousel.children[2].offsetLeft - carousel.children[1].offsetLeft - itemWidth;
      const step = itemWidth + itemMargin;

      // Use the native `scrollBy` method to perform a smooth scroll.
      // This will trigger the @scroll event, just like a manual swipe.
      carousel.scrollBy({
        left: step * direction,
        behavior: 'smooth',
      });

      // --- End of new logic ---
      // The old logic for calculating index and setting state is completely removed.
    },

    // 新增：处理滚动事件的方法
    handleScroll() {
      // 清除之前的计时器
      clearTimeout(this.scrollTimeout);
      // 设置一个新的计时器，如果在 150ms 内没有新的滚动事件，就认为滚动停止了
      this.scrollTimeout = setTimeout(() => {
        this.updateSingerAfterScroll();
      }, 150);
    },

    // UPDATE updateSingerAfterScroll to handle the loop jump
    updateSingerAfterScroll() {
      const carousel = this.$refs.singerCarousel;
      if (!carousel) return;

      const carouselCenter = carousel.scrollLeft + carousel.offsetWidth / 2;
      let closestDisplayIndex = -1;
      let minDistance = Infinity;

      for (let i = 0; i < carousel.children.length; i += 1) {
        const item = carousel.children[i];
        const itemCenter = item.offsetLeft + item.offsetWidth / 2;
        const distance = Math.abs(carouselCenter - itemCenter);
        if (distance < minDistance) {
          minDistance = distance;
          closestDisplayIndex = i;
        }
      }

      if (closestDisplayIndex === -1) return;

      const totalDisplayItems = this.displaySingerList.length;

      // THE LOOP LOGIC
      if (closestDisplayIndex === 0) {
        // We landed on the CLONED LAST item at the beginning
        // Silently jump to the REAL LAST item's position
        this.scrollToSinger(this.singerList.length - 1, 'auto');
      } else if (closestDisplayIndex === totalDisplayItems - 1) {
        // We landed on the CLONED FIRST item at the end
        // Silently jump to the REAL FIRST item's position
        this.scrollToSinger(0, 'auto');
      }

      // Update the state with the ID of the currently centered item
      const currentSinger = this.displaySingerList[closestDisplayIndex];
      if (currentSinger && this.currentTipSingerId !== currentSinger.awardid) {
        // Use a flag to prevent the watcher from triggering another scroll
        this.setCurrentTipSingerId(currentSinger.awardid);
      }
    },
    chooseGiftType(g) {
      this.setCurrentTipGiftType(g.giftId);
    },
    handleBlur() {
      window.scrollTo(0, -document.documentElement.clientHeight);
    },
    ganerateRandomWish() {
      this.content = QUICKWISH[generateRandom(0, quickWishLen)];
    },
    handleDeskInput(e) {
      this.setTipDeskNum(e.target.value);
    },
    handleSend() {
      // 校验桌号
      if (!this.tipDeskNum) {
        if (this.$toast && this.$toast.center) {
          this.$toast.center('请选择桌号');
        }
        return;
      }
      // 校验礼物
      if (!this.currentTipGiftType) {
        if (this.$toast && this.$toast.center) {
          this.$toast.center('请选择礼物');
        }
        return;
      }
      // 校验歌手
      if (!this.currentTipSingerId) {
        if (this.$toast && this.$toast.center) {
          this.$toast.center('请选择歌手');
        }
        return;
      }
      // 校验留言
      if (!this.content || !String(this.content).trim()) {
        if (this.$toast && this.$toast.center) {
          this.$toast.center('请输入留言内容');
        }
        return;
      }
      // 构造支付页面参数并跳转
      const { openId } = this.$store.state.user;
      const { userId } = this.$store.state.user;
      const giftId = this.currentTipGiftType;
      const singerId = this.currentTipSingerId;
      const singername = encodeURIComponent(this.selectedSingerName || '');
      const desknum = this.tipDeskNum;
      const content = encodeURIComponent(String(this.content).trim());

      const origin = 'sendTipGift';
      const url = `/pages/pay/pay?openId=${openId}&userId=${userId}&giftId=${giftId}&singerId=${singerId}&singername=${singername}&desknum=${desknum}&content=${content}&origin=${origin}`;
      try {
        wx.miniProgram.navigateTo({ url });
      } catch (e) {
        console.log('navigateTo pay error:', e, url);
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import 'vue-swipe/dist/vue-swipe.css';
.tipModule {
  position: absolute;
  width: 100%;
  bottom: 0;
  .tipBox {
    width: 750px;
    height: 97vh;
    background-image: url('../../assets/image/popupArea/chooseSongBg.png');
    background-size: 100% 100%;
    display: flex;
    flex-direction: column;
    position: relative;
    .closeIcon {
      width: 48px;
      height: 48px;
      position: absolute;
      right: 16px;
      top: 4px;
    }
    .tip-title-wrapper {
      height: 72px;
      max-width: calc(100% - 80px); /* 预留右侧关闭按钮空间 */
      min-width: 342px;
      padding: 0 32px;
      box-sizing: border-box;
      background-image: url('../../assets/image/container/singer-bg.png');
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: center;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40px;
      color: #FFFFFF;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    /* --- START: 轮播区域全新样式 (修正版) --- */
    .singer-carousel-container {
      width: 100%;
      position: relative; /* 为箭头绝对定位提供基准 */
      margin-top: 20px;
    }

    .arrow {
      /* 改为绝对定位，覆盖在轮播图之上 */
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      z-index: 10;
      width: 44px;
      height: 44px;
      background-color: rgba(0, 0, 0, 0.3); /* 增加背景色以提高可见性 */
      border-radius: 50%;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;

      /* 当歌手数量不足时隐藏箭头 */
      &.is-disabled {
        display: none;
      }

      &::after {
        content: '';
        display: block;
        width: 12px;
        height: 12px;
        border-style: solid;
        border-color: white;
        border-width: 0 2px 2px 0;
      }

      &.left-arrow {
        left: 32px; /* 距离左侧边缘的距离 */
        &::after {
          transform: translateX(2px) rotate(135deg);
        }
      }

      &.right-arrow {
        right: 32px; /* 距离右侧边缘的距离 */
        &::after {
          transform: translateX(-2px) rotate(-45deg);
        }
      }
    }

    .singer-carousel-wrapper {
      /* 宽度占满父容器，作为可视区域 */
      width: 100%;
      overflow: visible; /* 允许名字横幅显示 */
    }

    .singer-carousel {
      display: flex;
      /* 关键点1: 将 align-items 从 flex-start 改为 center */
      /* 这样缩小的卡片才能在垂直方向上保持居中 */
      align-items: center;
      overflow-x: auto;
      /* 隐藏滚动条 */
      -ms-overflow-style: none;
      scrollbar-width: none;
      &::-webkit-scrollbar {
        display: none;
      }
      /*
        左右 padding 保持不变，它确保了首尾卡片也能居中
      */
      padding: 40px 175px 20px;
      /* Add scroll snapping for better UX */
      scroll-snap-type: x mandatory;
    }

    .singer-item {
      position: relative;
      flex-shrink: 0; /* 防止项目被压缩，保持不变 */
      width: 400px;
      height: 300px;
      margin: 0 14px;
      border-radius: 14px;
      overflow: visible;
      display: flex;
      flex-direction: column;
      align-items: center;
      /* Add scroll snap alignment */
      scroll-snap-align: center;

      /* --- START: 这是新增/修改的核心样式 --- */

      /* 关键点2: 给所有卡片设置默认的缩小和半透明状态 */
      transform: scale(0.85); /* 默认将卡片缩小到85% */
      opacity: 0.7;           /* 默认透明度为70% */

      /* 关键点3: 添加平滑的过渡动画 */
      transition: transform 0.4s ease, opacity 0.4s ease;

      /* --- END: 这是新增/修改的核心样式 --- */

      .singer-name-banner {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        z-index: 5;
        max-width: 90%;
        min-width: 160px;
        height: 48px;
        padding: 0 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-image: url('../../assets/image/hdBar/nickname-container.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        background-position: center;
        font-size: 28px;
        color: #FFFFFF;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        box-sizing: border-box;
      }

      .singer-image {
        width: 100%;
        height: 100%;
        object-fit: cover; /* 保证图片不变形地填满容器 */
        display: block;
        border-radius: 14px;
      }

      .tick-icon {
        position: absolute;
        bottom: 16px;
        right: 16px;
        width: 48px;
        height: 48px;
        z-index: 10;
      }

      /* 关键点4: 覆盖 .selected 状态的样式 */
      &.selected {
        /* 当卡片被选中时，恢复正常大小和不透明度 */
        transform: scale(1);
        opacity: 1;

        /* 边框样式保持不变 */
        .singer-image {
          border: 4px solid #B15BFF;
          box-sizing: border-box;
        }
      }
    }

    .pagination-dots {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 20px;
      .dot {
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background-color: #ffffff;
        margin: 0 2px; /* 点之间的间距 */
        transition: background-color 0.3s;
        &.active {
          background-color: #dd01ff;
        }
      }
    }

    .return-button-container {
      width: 100%;
      display: flex;
      justify-content: flex-end;
      padding: 20px 32px 0;
      box-sizing: border-box;
      .return-button {
        display: flex;
        align-items: center;
        cursor: pointer;
        .return-text {
          font-size: 28px;
          color: #c7b7fe;
          margin-right: 8px;
        }
        .return-icon {
          width: 24px;
          height: 24px;
        }
      }
    }

    .tab-container {
      justify-content: flex-start;
      width: 100%;
      padding: 20px 32px 0;
      box-sizing: border-box;
      .tab-item {
        font-size: 30px;
        font-weight: 400;
        color: rgba(255, 255, 255, 0.6);
        flex-direction: column;
        &.active {
          color: #fff;
          &::after {
            display: block;
            content: '';
            width: 52px;
            height: 6px;
            background: #ffffff; /* 白色下划线 */
            border-radius: 20px;
            margin-top: 4px;
          }
        }
      }
    }
    /* --- END: 轮播区域全新样式 (修正版) --- */

    /* 礼物选择区域样式 */
    .giftListWrap {
      width: 100%;
      margin-top: 20px;
      height: 480px;
      .gift-swipe {
        .page {
          width: 100%;
          height: 100%;
          position: absolute;
          padding: 0 2%;
          .item {
            position: relative;
            flex-direction: column;
            margin: 24px 0;
            width: 25%;
            float: left;
            .giftImg {
              width: 85px;
              height: 85px;
              &.active {
                animation-name: bounceIn;
                animation-duration: 2.5s;
                animation-iteration-count: infinite;
                animation-delay: 0;
              }
            }
            .stubbleIcon {
              width: 84px;
              height: 40px;
              position: absolute;
              top: -10px;
              right: -30px;
            }
            .name {
              font-size: 24px;
              color: #fff;
              margin-top: 20px;
            }
            .price {
              margin-top: 6px;
              color: rgba(255, 255, 255, 0.6);
              font-size: 20px;
              .rmb {
                color: #FFD700;
                font-weight: 600;
                margin-right: 4px;
              }
            }
            .activeBox {
              position: absolute;
              top: -15px;
              width: 110px;
              height: 110px;
              border: 3px solid #ddd;
              border-image: linear-gradient(#e12b95, #cb63ee) 1 1;
            }
          }
        }
      }
      .mint-swipe::v-deep {
        .mint-swipe-items-wrap {
          position: relative;
          height: 100%;
        }
        .mint-swipe-indicators {
          display: flex;
          justify-content: center;
          position: absolute;
          bottom: 0;
          width: 100%;
          .mint-swipe-indicator {
            width: 6px;
            height: 6px;
            background-color: #ffffff;
            border-radius: 3px;
            margin: 0 4px;
            &.is-active {
              width: 10px;
            }
          }
        }
      }
    }

    /* 输入框区域样式 */
    .txtWrap {
      margin-top: auto  ;
      position: relative;
      textarea {
        width: 686px;
        height: 116px;
        font-size: 28px;
        padding: 20px 32px;
        padding-right: 100px;
        color: #fff;
        outline: none;
        box-sizing: border-box;
        background-color: transparent;
        border: 2px solid;
        border-image: linear-gradient(99deg, #45f6fe 0%, #c026ed 100%) 1 1;
        &::placeholder {
          font-size: 28px;
          color: #756ea1;
        }
      }
      .ylBtn {
        width: 88px;
        height: 48px;
        background: #231f44;
        border-radius: 10px;
        font-size: 28px;
        font-weight: 400;
        color: #c2baf5;
        position: absolute;
        top: 32px;
        right: 48px;
      }
    }

    /* 底部按钮区域样式 */
    .btnWrap {
      margin-top: 48px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding-left: 32px;
      padding-right: 32px;
      margin-bottom: 32px;
      box-sizing: border-box;
      position: relative;
      .selectDeskInput {
        width: 200px;
        height: 80px;
        background: #5412a9;
        border-radius: 12px;
        font-size: 32px;
        font-weight: 400;
        color: #ffffff;
        flex-shrink: 0;
        border: none;
        text-align: center;
        outline: none;
        &::placeholder {
          color: rgba(255, 255, 255, 0.6);
        }
      }
      .sendBtn {
        width: 128px;
        height: 52px;
        background: linear-gradient(300deg, #c76bfb 0%, #ea1775 100%);
        background-image: url('../../assets/image/hdBar/sendBtn.png');
        background-size: 100% 100%;
        font-size: 32px;
        color: #ffffff;
        flex-shrink: 0;
      }
    }

  }
}
</style>
